package com.example.parallelandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.parallelandroid.entity.User;
import com.example.parallelandroid.entity.UserInfo;
import com.example.parallelandroid.novicedialog.IPickDialog;
import com.example.parallelandroid.novicedialog.PickDialog;
import com.example.parallelandroid.utils.EncryptUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import cn.bmob.v3.encry.binary.StringUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SettingPasswordActivity extends AppCompatActivity implements IPickDialog {
    EditText edtPassword, edtConfirmPassword;
    Button btnSave;
    SharedPreferences sharedPreferences;
    private PickDialog pickDialog;
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private int[] imgSrc = {R.mipmap.novice1, R.mipmap.novice2,R.mipmap.novice3,R.mipmap.novice4,
            R.mipmap.novice5,R.mipmap.novice6,R.mipmap.novice7,R.mipmap.novice8};
    int pos = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_password);

        sharedPreferences = getSharedPreferences("user",
                MODE_PRIVATE);
        getView();
        initView();
        //密码限制
        edtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String pwd = edtPassword.getText().toString();
                if (TextUtils.isEmpty(pwd) && "".equals(pwd)) {
                    edtPassword.setError("请输入密码");
                } else {
                    if (pwd.length() >= 8 && pwd.length() <= 15) {

                    } else {
                        edtPassword.setError("请输入8到15位密码，包含大小写字母、数字、特殊字符");

                    }
                }
            }
        });

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String password1 = edtPassword.getText().toString();
                String password2 = edtConfirmPassword.getText().toString();
                if (password1 == null || password1.equals("")) {
                    Toast.makeText(SettingPasswordActivity.this, "密码不能为空", Toast.LENGTH_LONG).show();
                } else if (password2 == null || password2.equals("")) {
                    Toast.makeText(SettingPasswordActivity.this, "确认密码不能为空", Toast.LENGTH_LONG).show();
                } else if (!password1.equals(password2)) {
                    Toast.makeText(SettingPasswordActivity.this, "两次密码不一致,请重新输入", Toast.LENGTH_LONG).show();
                } else if(!checkPassword(password2)){
                    Toast.makeText(SettingPasswordActivity.this, "请输入8到15位密码，包含大小写字母、数字、特殊字符", Toast.LENGTH_LONG).show();
                }else {
                    //存入手机号和密码
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    String phone = sharedPreferences.getString("phone", "");
                    editor.putString("password", password1);
                    editor.commit();
                    save(phone, EncryptUtils.encrypt(password1));
                    pos = 0;
                    if (pickDialog != null && pickDialog.isShowing()) {
                        return;
                    }
                    dialog(pos);
                }
            }
        });
        //初始化对话框，设置接口
        pickDialog = new PickDialog(this, R.style.NoviceDialog);
        pickDialog.setiPickDialog(this);
    }

    private void initView() {
        EditText passwordEdit = findViewById(R.id.edt_password);
        LinearLayout passLayout = findViewById(R.id.passwordLayout);
        View passView1 = findViewById(R.id.passwordView1);
        View passView2 = findViewById(R.id.passwordView2);

        passwordEdit.addTextChangedListener(new TextWatcher() {
             @Override
             public void beforeTextChanged(CharSequence s, int start, int count, int after) {

             }

             @Override
             public void onTextChanged(CharSequence s, int start, int before, int count) {

             }
             @Override
             public void afterTextChanged(Editable s) {
                 if(s.toString().length() > 0){
                     if(s.toString().length() == 1)
                         passLayout.setVisibility(View.VISIBLE);
                     switch (checkPassWord(s.toString())){
                         case 1:
                             passView1.setVisibility(View.GONE);
                             passView2.setVisibility(View.GONE);
                             break;
                         case 2:
                             passView1.setVisibility(View.VISIBLE);
                             passView2.setVisibility(View.GONE);
                             break;
                         case 3:
                             passView2.setVisibility(View.VISIBLE);
                             break;
                     }
                 }else{
                     passLayout.setVisibility(View.GONE);
                 }
             }         
        });
    }

    private int checkPassWord(String passwordStr) {
        String regexZ = "\\d*";
        String regexS = "[a-zA-Z]+";
        String regexT = "\\W+$";
        String regexZT = "\\D*";
        String regexST = "[\\d\\W]*";
        String regexZS = "\\w*";
        String regexZST = "[\\w\\W]*";
        int pass = 0;
        if (passwordStr.matches(regexZ)) {
            return 1;
        }
        if (passwordStr.matches(regexS)) {
            return 1;
        }
        if (passwordStr.matches(regexT)) {
            return 1;
        }
        if (passwordStr.matches(regexZT)) {
            return 2;
        }
        if (passwordStr.matches(regexST)) {
            return 2;
        }
        if (passwordStr.matches(regexZS)) {
            return 2;
        }
        if (passwordStr.matches(regexZST)) {
            return 3;
        }
        return pass;
    }

    private boolean checkPassword(String password2) {
        boolean capitalFlag = false;
        boolean lowerCaseFlag = false;
        boolean numberFlag = false;
        boolean numLength = false;
        boolean res = false;
        // 获取用户输入的新密码
        String newPwd = password2;
        for (int i=0; i<newPwd.length(); i++) {
            Character ch = newPwd.charAt(i);
            if( Character.isDigit(ch)) {
                numberFlag = true;
            } else if (Character.isUpperCase(ch)) {
                capitalFlag = true;
            } else if (Character.isLowerCase(ch)) {
                lowerCaseFlag = true;
            }
        }
        if (newPwd.length() >= 8 && newPwd.length() <= 15){
            numLength = true;
        }
        if(numberFlag && capitalFlag && lowerCaseFlag && numLength) {
            res = true;
        }
        return res;
    }

    private void dialog(int pos) {
        pickDialog.initImage(imgSrc[pos]);
        pickDialog.show();
        // 将对话框的大小按屏幕大小的百分比设置
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = pickDialog.getWindow().getAttributes();
        lp.width = (display.getWidth() * 1); //设置宽度
        pickDialog.getWindow().setAttributes(lp);
    }
    public void onLast() {
        int src = imgSrc[pos];
        if (pos > 0) {
            pos = pos - 1;
        } else if (pos == 0) {
            //Toast.makeText(this, "已经是第一条数据了", Toast.LENGTH_SHORT).show();
        }
        pickDialog.initImage(imgSrc[pos]);
    }


    @Override
    public void onNext() {
        int src = imgSrc[pos];
        if (pos == imgSrc.length - 1) {
            //Toast.makeText(this, "已经是最后一条数据了", Toast.LENGTH_SHORT).show();
            pickDialog.dismiss();
            //新手教程展示最后一条，跳转页面
            Intent intent = new Intent(SettingPasswordActivity.this, MainFromActivity.class);
            startActivity(intent);
            finish();
            //填充代码
        } else if (pos >= 0) {
            ++pos;
        }
        pickDialog.initImage(imgSrc[pos]);
    }

    @Override
    public void onConfirm(String address) {
        int src = imgSrc[pos];
    }



    private void createUserInfo() {
        UserInfo userInfo = new UserInfo();
        String userId = sharedPreferences.getString("userId","");
        String phone = sharedPreferences.getString("phone","");
        int avatar = (int) (Math.random() * 12 + 1);
        userInfo.setUserId(userId);
        userInfo.setCharm(0.000);
        userInfo.setComprehensive(0.000);
        userInfo.setIntelligence(0.000);
        userInfo.setPower(0.000);
        userInfo.setTodayLearningTime(0.00);
        userInfo.setIsVip(0);
        userInfo.setTodayStep(0);
        userInfo.setWearWeapon("https://tlryjg.jiaohusheji.net/wp-content/uploads/2019/12/mujian.png");
        userInfo.setWearSuit("https://tlryjg.jiaohusheji.net/wp-content/uploads/2021/11/1636462787-Archaeologist27s_set.png");
        userInfo.setSuitStore("{\"a\":1}");
        userInfo.setWeaponStore("{\"a\":1}");
        userInfo.setAvatar(avatar + "");
        userInfo.setNickName("用户" + phone);
        OkHttpClient okHttpClient = new OkHttpClient();
        String json = new Gson().toJson(userInfo);
        RequestBody requestBody = RequestBody.create(JSON,json);
        Constant.logger.info("开始向服务端传输UserInfo userId=" + userInfo.getUserId());
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "userInfo/createUserInfo")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Constant.logger.warn("向服务端传输UserInfo: 失败", e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String json = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    String msg = jsonObject.getString("msg");
                    Constant.logger.info("服务端Response: " + msg);
                } catch (JSONException e) {
                    Constant.logger.warn("解析服务端Response: 失败", e);
                }
            }
        });
    }

    //存入新用户的账号密码
    private void save(String userName,String password) {
        Log.d("保存账号密码","begin");
        OkHttpClient okHttpClient = new OkHttpClient();
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        String json = new Gson().toJson(user);
        RequestBody requestBody = RequestBody.create(JSON,json);
        Constant.logger.info("开始向服务端传输新用户的账号密码 userName=" + user.getUserName());
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "user/createUser")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Constant.logger.warn("向服务端传输新用户的账号密码: 失败", e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String json = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    String msg = jsonObject.getString("msg");
                    Constant.logger.info("服务端Response: " + msg);
                    String jsonStr = jsonObject.getString("data");
                    if(!(jsonStr == null || "".equals(jsonStr) || "null".equals(jsonStr))){
                        Gson gson = new Gson();
                        User user = gson.fromJson(jsonStr,User.class);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        Log.e("userId",user.getUserId());
                        editor.putString("userId",user.getUserId());
                        editor.commit();
                    }
                    createUserInfo();
                } catch (JSONException e) {
                    Constant.logger.warn("解析服务端Response: 失败", e);
                }
            }
        });
    }

    private void getView() {
        edtPassword = findViewById(R.id.edt_password);
        edtConfirmPassword = findViewById(R.id.edt_confirm_password);
        btnSave = findViewById(R.id.btn_save);
    }


}
